{% extends "base.html" %}

{% block content %}
<div class="row mb-4">
    <div class="col-12">
        <div class="card">
            <div class="card-body">
                <h5 class="card-title">数据访问流程</h5>
                <div id="dynamicFlow" class="flow-diagram">
                    <!-- 左侧：客户端 -->
                    <div class="flow-node client" style="background: #f9f; position: absolute; left: 50px; top: 50%;">
                        <i class="fas fa-laptop"></i>
                        <div>客户端</div>
                    </div>
                    
                    <!-- 中间：Redis -->
                    <div class="flow-node redis" style="background: #f66; position: absolute; left: 40%; top: 20px;">
                        <i class="fas fa-database"></i>
                        <div>Redis缓存</div>
                        <div class="cache-status"></div>
                    </div>
                    
                    <!-- 右侧：MySQL -->
                    <div class="flow-node mysql" style="background: #69f; position: absolute; right: 50px; top: 50%;">
                        <i class="fas fa-database"></i>
                        <div>MySQL</div>
                    </div>
                    
                    <!-- 连接线 -->
                    <svg class="flow-lines" style="position: absolute; width: 100%; height: 100%; top: 0; left: 0;">
                        <path class="path-to-redis" d="M0,0 L0,0" stroke="#333" stroke-width="2" fill="none"/>
                        <path class="path-to-mysql" d="M0,0 L0,0" stroke="#333" stroke-width="2" fill="none"/>
                        <path class="path-back" d="M0,0 L0,0" stroke="#333" stroke-width="2" fill="none"/>
                    </svg>
                    
                    <div id="flowAnimation"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-md-6">
        <div class="card">
            <div class="card-body">
                <h5 class="card-title">创建新用户</h5>
                <form id="createUserForm">
                    <div class="mb-3">
                        <label for="username" class="form-label">用户名</label>
                        <input type="text" class="form-control" id="username" required>
                    </div>
                    <div class="mb-3">
                        <label for="email" class="form-label">邮箱</label>
                        <input type="email" class="form-control" id="email" required>
                    </div>
                    <button type="submit" class="btn btn-primary">创建用户</button>
                </form>
            </div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="card">
            <div class="card-body">
                <h5 class="card-title">查询用户</h5>
                <form id="getUserForm">
                    <div class="mb-3">
                        <label for="userId" class="form-label">用户ID</label>
                        <input type="number" class="form-control" id="userId" required>
                    </div>
                    <button type="submit" class="btn btn-primary">查询</button>
                </form>
                <div id="userResult" class="mt-3"></div>
            </div>
        </div>
    </div>
</div>

<script>
class FlowAnimation {
    constructor() {
        this.flowDiv = document.getElementById('dynamicFlow');
        this.animationDiv = document.getElementById('flowAnimation');
        this.cacheStatus = document.querySelector('.cache-status');
        this.setupNodes();
        this.drawConnections();
    }

    setupNodes() {
        const nodes = this.flowDiv.getElementsByClassName('flow-node');
        const positions = {};
        Array.from(nodes).forEach(node => {
            const rect = node.getBoundingClientRect();
            const flowRect = this.flowDiv.getBoundingClientRect();
            positions[node.classList[1]] = {
                x: rect.left - flowRect.left + rect.width / 2,
                y: rect.top - flowRect.top + rect.height / 2,
                width: rect.width,
                height: rect.height
            };
        });
        this.positions = positions;
    }

    drawConnections() {
        const svg = this.flowDiv.querySelector('.flow-lines');
        const paths = {
            toRedis: svg.querySelector('.path-to-redis'),
            toMySQL: svg.querySelector('.path-to-mysql'),
            back: svg.querySelector('.path-back')
        };

        // 绘制连接线
        const {client, redis, mysql} = this.positions;
        paths.toRedis.setAttribute('d', `M${client.x},${client.y} Q${(client.x + redis.x)/2},${client.y} ${redis.x},${redis.y}`);
        paths.toMySQL.setAttribute('d', `M${redis.x},${redis.y} Q${(redis.x + mysql.x)/2},${redis.y} ${mysql.x},${mysql.y}`);
        paths.back.setAttribute('d', `M${redis.x},${redis.y} Q${(client.x + redis.x)/2},${redis.y} ${client.x},${client.y}`);
    }

    async animateFlow(path, hasCache) {
        this.animationDiv.innerHTML = '';
        this.cacheStatus.textContent = hasCache ? '缓存命中' : '缓存未命中';
        this.cacheStatus.style.color = hasCache ? '#4CAF50' : '#FFC107';

        for (let i = 0; i < path.length - 1; i++) {
            const start = this.positions[path[i]];
            const end = this.positions[path[i + 1]];
            await this.animateDot(start, end);
        }
    }

    animateDot(start, end) {
        return new Promise(resolve => {
            const dot = document.createElement('div');
            dot.className = 'flow-dot';
            dot.style.left = `${start.x}px`;
            dot.style.top = `${start.y}px`;
            this.animationDiv.appendChild(dot);

            // 添加数据包图标
            dot.innerHTML = '<i class="fas fa-database" style="font-size: 12px;"></i>';

            setTimeout(() => {
                dot.style.left = `${end.x}px`;
                dot.style.top = `${end.y}px`;
                setTimeout(() => {
                    dot.remove();
                    resolve();
                }, 800);
            }, 100);
        });
    }
}

// 初始化流程图动画
const flowAnimation = new FlowAnimation();

document.getElementById('createUserForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const response = await fetch('/user', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            username: document.getElementById('username').value,
            email: document.getElementById('email').value
        })
    });
    const data = await response.json();
    alert(`用户创建成功！用户ID: ${data.user_id}`);
    document.getElementById('createUserForm').reset();
});

document.getElementById('getUserForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const userId = document.getElementById('userId').value;
    
    // 开始动画
    const response = await fetch(`/user/${userId}`);
    const data = await response.json();
    
    // 根据数据来源选择动画路径
    if (data.source === 'redis') {
        await flowAnimation.animateFlow(['client', 'redis', 'client'], true);
    } else {
        await flowAnimation.animateFlow(['client', 'redis', 'mysql', 'redis', 'client'], false);
    }
    
    // 显示结果
    const resultDiv = document.getElementById('userResult');
    resultDiv.innerHTML = `
        <div class="card">
            <div class="card-body">
                <h6 class="card-subtitle mb-2 text-muted">
                    用户信息
                    <span class="badge ${data.source === 'redis' ? 'redis-badge' : 'mysql-badge'} source-badge">
                        ${data.source === 'redis' ? 'From Redis' : 'From MySQL'}
                    </span>
                </h6>
                <p><strong>ID:</strong> ${data.user.id}</p>
                <p><strong>用户名:</strong> ${data.user.username}</p>
                <p><strong>邮箱:</strong> ${data.user.email}</p>
                <p><strong>创建时间:</strong> ${new Date(data.user.created_at).toLocaleString()}</p>
                <div class="timing-info">
                    <p><strong>查询耗时:</strong> ${data.query_time}ms</p>
                </div>
            </div>
        </div>
    `;
});
</script>
{% endblock %} 